#ifndef SEGMENTINVENTORY_H_INCLUDED
#define SEGMENTINVENTORY_H_INCLUDED

#include "BufferManager.h"
#include <vector>
#include <stdio.h>
#include <string.h>
#include <list>

class SegmentInventory
{
public:
    vector<unsigned> requestPages(unsigned segmentId, unsigned min, unsigned max);
    void returnPages(unsigned segId, vector<unsigned> pages);
    unsigned getFreeCount(); //for testing purposes
    ~SegmentInventory();

    void printInventory();
#ifdef DEBUG
    static void testMerge();
#endif
protected:

private:
    SegmentInventory(unsigned pageCount, BufferManager& buffMan);

    struct Entry;
    struct Segment;

    unsigned pageCount;
    unsigned freeCount;
    vector<SegmentInventory::Segment*> segments;
    vector< vector<SegmentInventory::Entry*> > entries;
    SEMAPHORE fileSemaphore;

    unsigned grow();

    void loadInventory();
    void saveInventory();
    void createInventory(BufferManager& buffMan);
    void clear();

    static void merge(vector<SegmentInventory::Entry*>& entries, list<unsigned>& pages);
    static list<unsigned>* removeIfContained(vector<SegmentInventory::Entry*>& entries, list<unsigned>& pages);

    friend class DB;
};

struct SegmentInventory::Entry
{
    unsigned from;
    unsigned to;
};

struct SegmentInventory::Segment
{
    unsigned segmentId;
    unsigned entryCount;
};


#endif // SEGMENTINVENTORY_H_INCLUDED
